extends State



@onready var update_pos_timer: Timer = $UpdatePosTimer
@onready var speed_reduction_timer: Timer = $SpeedReductionTimer
# @onready var _player: Player = get_tree().get_first_node_in_group("player")

## 受到攻击时，移动速度降低
@export var _speed_reduction_factor: float = 0.5

var _enemy: Enemy
var _next_pos:  Vector2
var _speed_r_factor: float = 1.0



func _ready() -> void:
    _enemy = _root.target

    # 更新寻路下一目标位置
    update_pos_timer.timeout.connect(
        func()  ->  void:
            _enemy.navigation_agent.target_position = Global.get_player().center_position()
    )

    # 结束受击减速
    speed_reduction_timer.timeout.connect(
        func() -> void:
            _speed_r_factor = 1.0
    )

    await _enemy.ready
    _enemy.navigation_agent.velocity_computed.connect(
        func(safe_velocity: Vector2) -> void:
            _enemy.velocity = safe_velocity  * _speed_r_factor
    )

    # 开始受击减速
    _enemy.handle_damage_signals.receive_damage_applied.connect(
        func(_info: DamageInfo) -> void:
            _speed_r_factor =  _speed_reduction_factor
            speed_reduction_timer.start()
    )


func _enter() -> void:
    _root.amt_player.play("move")


func _update(_delta: float) -> void:
    var direction := _enemy.center_position().direction_to(_next_pos)
    var velocity := direction * _enemy.data.speed.value
    
    if  _enemy.navigation_agent.avoidance_enabled:
        _enemy.navigation_agent.velocity = velocity
        # _enemy.navigation_agent.max_speed = velocity.length()
    else:
        _enemy.velocity = velocity * _speed_r_factor
    
    if _enemy.data.health.value <= 0:
        switch.emit("Dead")



func _fixed_update(_delta: float) -> void:
    _next_pos = _enemy.navigation_agent.get_next_path_position()
    _enemy.move_and_slide()
